package edu.ncsu.csc;

import java.io.IOException;

import com.sun.squawk.util.StringTokenizer;

public class Configuration {
	private static final int MAX_SENSORS = 8;
	private static final int SENSOR_TYPES = 7;

	private byte[] sensorTypes;
	
	public Configuration() {
		this(new byte[0]);
	}
	
	public Configuration(byte[] sensorTypes) {
		this.sensorTypes = sensorTypes;
	}	

	public byte[] getSensorTypes() {
		return sensorTypes;
	}

	public void setSensorTypes(byte[] sensorTypes) {
		if (sensorTypes.length >= MAX_SENSORS) throw new IllegalArgumentException("Too many sensors: " + sensorTypes.length);
		
		for (int i = 0; i < sensorTypes.length; i++)
			if (sensorTypes[i] < 0 || sensorTypes[i] >= SENSOR_TYPES)
				throw new IllegalArgumentException("Invalid sensor type: " + sensorTypes[i]);
		
		this.sensorTypes = sensorTypes;
	}

	public static Configuration loadFromSystemProperties() throws IllegalArgumentException, IOException {
		String sensorsStr = System.getProperty("SensorSPOT.sensors");

		if (sensorsStr == null) return null;

		StringTokenizer st = new StringTokenizer(sensorsStr, ",");

		byte[] sensors;
		try {
			sensors = new byte[st.countTokens()];
			for (int i = 0; st.hasMoreTokens() && i < sensors.length; i++) sensors[i] = Byte.parseByte(st.nextToken());
		} catch (NumberFormatException nfe) { throw new IOException("Corrupted sensors types system property: " + sensorsStr);	}
		
		return new Configuration(sensors);
	}
}
